package org.ssm.demo.service.export;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.ssm.demo.cache.RedisCacheManager;
import org.ssm.demo.entity.User;
import org.ssm.demo.service.IUserService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import static org.ssm.demo.utils.DomParserUtils.ExportXMLMethod;
import static org.ssm.demo.utils.DomParserUtils.ExportXMLMethod1;
import static org.ssm.demo.utils.DomParserUtils.getOneXML;
import static org.ssm.demo.utils.ThreadUtils.getIndex;

/**
 * 配置spring和junit整合，junit启动时加载springIOC容器 spring-test,junit
 */
@RunWith(SpringJUnit4ClassRunner.class)
// 告诉junit spring配置文件
@ContextConfiguration({ "classpath:applicationContext.xml"})
public class ExportTest1 {

    @Autowired
    private RedisCacheManager redisCacheManager;

    @Autowired
    public IUserService userService;

    @Test
    public void getLimitAndExport(){
        int title = 0;
        int minSize = 100;//单个线程最小执行数量
        int maxTaskNum = 5;//最大线程数
        int count = 10000;//总数
        int[] indexs = getIndex(count,minSize,maxTaskNum);//根据总数，线程数，计算各个任务开始的下标
//        System.out.print("[");
//        for(int i = 0;i<indexs.length;i++){
//            System.out.print(indexs[i]+",");
//        }
//        System.out.println("]");
        int offset = indexs[1] - indexs[0];

        Map<Integer,String> map = new HashMap<Integer,String>();
        Map<Integer,String> map1 = new HashMap<Integer,String>();

        //单线程
        long startTime = System.currentTimeMillis();
        for(int i=0;i<indexs.length-1;i++){
            //读数据库的方式
            map.put(i,ExportXMLMethod(userService.getLimit(indexs[i],offset),title));
            //读缓存的方式
//            List<String> list = new ArrayList<>();
//            for(int j=0;j<redisCacheManager.lGet("userlist",indexs[i],indexs[i]+offset).size();j++){
//                list.add(redisCacheManager.lGet("userlist",indexs[i],indexs[i]+offset).get(j).toString());
//            }
//            map1.put(i,ExportXMLMethod1(list,title));
            title++;
        }
        long endTime = System.currentTimeMillis();
        System.out.println("程序运行时间：" + (endTime - startTime) + "ms");//输出程序运行时间

//        long startTime2 = System.currentTimeMillis();
//        getOneXML(map);//合并各个xml文件
//        long endTime2 = System.currentTimeMillis();
//        System.out.println("合并程序运行时间：" + (endTime2 - startTime2) + "ms");//输出程序运行时间

    }
}
